package cn.b.sky.mes.qm.controller;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.qm.model.Defect;
import cn.b.sky.mes.qm.model.DefectAttribute;
import cn.b.sky.mes.qm.model.DefectAttributeValue;
import cn.b.sky.mes.qm.model.condition.DefectCondition;
import cn.b.sky.mes.qm.service.DefectAttributeService;
import cn.b.sky.mes.qm.service.DefectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.controller.SecurityController;

/**
 * <strong>Title : DefectController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.qm.controller<br></strong>
 * <strong>Description : </strong>缺陷控制器<br> 
 * <strong>Create on : 2015年12月15日 下午1:53:48<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/defect/*")
public class DefectController extends SecurityController {

  @Resource
  DefectService defectService;

  @Resource
  DefectAttributeService defectAttributeService;

  @RequestMapping("defect_list")
  public String selectDefectListByCondition(@ModelAttribute("condition") DefectCondition condition, String navTabId,
                                            Model model) {
    condition.setSiteCode(getSiteCode());
    List<Defect> list = defectService.selectDefectListByCondition(condition);
    int count = defectService.selectDefectCountByCondition(condition);

    condition.setTotalCount(count);
    condition.setData(list);

    List<DefectAttribute> defectAttribute = defectAttributeService.selectDefectAttributeAndEnumByLockFlag(
        getSiteCode(), null);
    model.addAttribute("defectAttribute", defectAttribute);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "qm/defect/defect_list";
  }

  @RequestMapping("addDefect")
  public String addDefect(String navTabId, Model model) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("pattern", "add");
    List<DefectAttribute> defectAttribute = defectAttributeService.selectDefectAttributeAndEnumByLockFlag(
        getSiteCode(), 0);
    model.addAttribute("defectAttribute", defectAttribute);
    return "qm/defect/defect_add";
  }

  @RequestMapping("modifyDefect")
  public String modifyDefect(String id, String navTabId, Model model) {
    Defect defect = defectService.getDefect(id, getSiteCode());
    //缺陷属性,类型,及枚举列表
    List<DefectAttribute> defectAttribute = defectAttributeService.selectDefectAttributeAndEnumByLockFlag(
        getSiteCode(), 0);
    //缺陷属性及属性值
    List<DefectAttributeValue> defectAttributeValue = defectAttributeService.getAllDefectAttributeAndValue(id,
        getSiteCode());
    defect.getDefectAttributeValue().addAll(defectAttributeValue);

    setAttributeValue(defect, defectAttribute);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("defect", defect);
    model.addAttribute("defectAttribute", defectAttribute);
    model.addAttribute("pattern", "modify");

    return "qm/defect/defect_add";
  }

  private void setAttributeValue(Defect defect, List<DefectAttribute> defectAttribute) {
    if (defect.getDefectAttributeValue() == null) {
      return;
    }
    for (int i = 0; i < defect.getDefectAttributeValue().size(); i++) {
      DefectAttributeValue dav = defect.getDefectAttributeValue().get(i);
      if (StringUtils.isBlank(dav.getAttributeCode())) {
        continue;
      }
      for (int j = 0; j < defectAttribute.size(); j++) {
        DefectAttribute da = defectAttribute.get(j);
        if (StringUtils.isBlank(da.getAttributeCode())) {
          continue;
        }
        if (dav.getAttributeCode().equals(da.getAttributeCode())) {
          da.setAttributeValue(dav.getAttributeValue());
        }
      }
    }
  }

  @RequestMapping("viewDefect")
  public String viewDefect(String id, String navTabId, Model model) {
    Defect defect = defectService.getDefect(id, getSiteCode());
    //缺陷属性,类型,及枚举列表
    List<DefectAttribute> defectAttribute = defectAttributeService.selectDefectAttributeAndEnumByLockFlag(
        getSiteCode(), 0);
    //缺陷属性及属性值
    List<DefectAttributeValue> defectAttributeValue = defectAttributeService.getAllDefectAttributeAndValue(id,
        getSiteCode());
    defect.getDefectAttributeValue().addAll(defectAttributeValue);

    setAttributeValue(defect, defectAttribute);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("defect", defect);
    model.addAttribute("defectAttribute", defectAttribute);
    model.addAttribute("pattern", "view");

    return "qm/defect/defect_view";
  }

  @RequestMapping("saveDefect")
  @ResponseBody
  public DWZResult saveDefect(String id, Defect defect, String navTabId, Model model) {
    if (defect == null || StringUtils.isBlank(defect.getDefectCode())) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }

    defect.setSiteCode(getSiteCode());
    setCreateInfo(defect);
    if (defect.getLockFlag() == null) {
      defect.setLockFlag(0);
    }
    if (defect.getPictureFlag() == null) {
      defect.setPictureFlag(0);
    }
    if (StringUtils.isBlank(id)) {
      defectService.insertDefect(defect);
    } else {
      defectService.updateDefect(defect);
    }
    return dialogAjaxDone(
        getImeViewMessageI18n(null, "successfulOperation.M"),
        navTabId, null, null, null);
  }

  @RequestMapping("deleteDefect")
  @ResponseBody
  public DWZResult deleteDefect(String navTabId, Model model, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }

    String[] idArr = ids.split(",");
    BatchJobReport[] reports = new BatchJobReport[idArr.length];
    int failures = 0;
    for (int i = 0; i < idArr.length; i++) {
      reports[i] = defectService.deleteDefect(getSiteCode(), idArr[i]);
      if (!reports[i].isSuccess()) {
        failures += 1;
      }
    }

    if (failures == 0) {
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone(request, Arrays.asList(reports));
    }
  }

  @RequestMapping("validateDefectCode")
  @ResponseBody
  public boolean validateDefectCode(String defectCode) {
    if (StringUtils.isBlank(defectCode)) {
      return true;
    } else {
      Defect level = defectService.getDefect(defectCode, getSiteCode());
      return level == null;
    }
  }

  @RequestMapping("defectLookUp")
  public String defectLookUp(Model model, String lookupType, @ModelAttribute("condition") DefectCondition condition) {
    condition.setSiteCode(getSiteCode());
    condition.setLockFlag(0);
    List<Defect> list = defectService.selectDefectListByCondition(condition);
    int count = defectService.selectDefectCountByCondition(condition);

    condition.setTotalCount(count);
    condition.setData(list);

    model.addAttribute("page", condition);
    if (!StringUtils.isBlank(lookupType) && "radio".equals(lookupType)) {
      return "qm/defect/defect_lookup_radio";
    }
    return "qm/defect/defect_lookup";
  }

  @RequestMapping("defectSuggest")
  @ResponseBody
  public Object defectSuggest(Model model, String suggestTest) {
    if (StringUtils.isBlank(suggestTest)) {
      return null;
    }
    DefectCondition condition = new DefectCondition();
    condition.setDefectCode(suggestTest);
    condition.setSiteCode(getSiteCode());
    condition.setLockFlag(0);
    return defectService.selectDefectListSuggestByCondition(condition);
  }
}
